package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustocmException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        dishService.saveWithFlavor(dishDto);
        return R.success("新增菜品成功!");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    /*@GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        //分页构造器
        Page<Dish> dishPage=new Page<>(page,pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage,lqw);

        //处理分页集合数据
        Page<DishDto> dishDtoPage = new Page<>();
        //复制分页信息(排除分页集合数据 没有分类名称)
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");

        //单独出来集合数据
        //获取原始dishPage分页对象中集合数据
        List<Dish> records = dishPage.getRecords();

        List<DishDto> dtoList=new ArrayList<>();
        //遍历集合
        records.forEach(dish -> {
            //创建一个DishDto对象
            DishDto dishDto=new DishDto();
            //复制dish数据到dishDto
            BeanUtils.copyProperties(dish,dishDto);
            //查询分类名称
            Category category = categoryService.getById(dish.getCategoryId());
            //设置分类名称到dishDto中
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }
            dtoList.add(dishDto);
        });
        //将处理后的集合 添加到分页对象
        dishDtoPage.setRecords(dtoList);
        return R.success(dishDtoPage);
    }*/
    // 复盘
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Dish> dishPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        lqw.orderByDesc(Dish::getUpdateTime);
        dishService.page(dishPage,lqw);

        Page<DishDto> dishDtoPage=new Page<>();
        List<DishDto> dtoList=new ArrayList<>();
        BeanUtils.copyProperties(dishPage,dishDtoPage,"records");
        List<Dish> records = dishPage.getRecords();
        records.forEach(dish -> {
            DishDto dishDto=new DishDto();
            BeanUtils.copyProperties(dish,dishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            if (category!=null){
                dishDto.setCategoryName(category.getName());
            }
            dtoList.add(dishDto);
        });
        dishDtoPage.setRecords(dtoList);
        return R.success(dishDtoPage);
    }



    /**
     * 修改数据回显 根据id查看
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto=dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        dishService.updateWithFlavor(dishDto);
        //清除缓存的方式
        //1 全局清理 dish_* 获取所有以dish_xxx开头的key
        //Set keys=redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        //2 精准清理  清理某个分类下面的菜品缓存数据
        redisTemplate.delete("dish_"+dishDto.getCategoryId()+"_1");
        return R.success("菜品修改成功!");
    }

    /**
     * 根据条件查询菜品
     * @param dish
     * @return
     */

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        //查询redis数据库缓存
        String key="dish_"+dish.getCategoryId()+"_1";
        List<DishDto> dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);

        //判断缓存是否有数据 若有 直接返回缓存数据
        if (dishDtoList!=null){
            return R.success(dishDtoList);
        }
        //若无 查询数据库

        //条件构造器
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件 查询菜品状态是1的
        lqw.eq(Dish::getStatus,1);
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //查询
        List<Dish> list = dishService.list(lqw);

        //复制dish-->dishDto
        List<DishDto> dtoList=new ArrayList<>();
        list.forEach(d -> {
            //创建一个Dto对象
            DishDto dishDto=new DishDto();
            //复制dish数据到dishDto
            BeanUtils.copyProperties(d,dishDto);
            //查询菜品口味数据
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,d.getId());
            List<DishFlavor> list1 = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(list1);
            dtoList.add(dishDto);
            //将查询的数据 放入缓存
            redisTemplate.opsForValue().set(key,dtoList,60, TimeUnit.MINUTES);
        });
        return R.success(dtoList);
    }

    /**
     * 修改菜品状态
     * @param type
     * @param ids
     * @return
     */
    @PostMapping("status/{type}")
    public R<String> status(@PathVariable int type,@RequestParam List<Long> ids){
        // 停售是 0  启售是 1
        if (type==0){
            for (Long id : ids) {
                Dish dish = dishService.getById(id);
                dish.setStatus(0);
                dishService.updateById(dish);
            }
        }else {
            for (Long id : ids) {
                Dish dish = dishService.getById(id);
                dish.setStatus(1);
                dishService.updateById(dish);
            }
        }
        return R.success("状态修改成功!");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        dishService.deleteWithFlavor(ids);
        return R.success("删除菜品成功!");
    }
}
